package com.yuwenchao.superafflatus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuwenchao.superafflatus.pojo.entity.SuperBookfile;
import com.yuwenchao.superafflatus.service.SuperBookfileService;
import com.yuwenchao.superafflatus.utils.DownloadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ChaooGG
 * @since 2021-05-31
 */
//@RestController
@Api(tags = "书籍下载管理")
@Controller
//@RequestMapping("/superBookfile")
public class SuperBookfileController {

    //从配置文件中取路径值
    @Value("${linuxFile.bookFile}")
    private String bookFile;


    @Value("${linuxFile.bookTemp}")
    private String bookTemp;

    @Autowired
    SuperBookfileService superBookfileService;

   //   String path =AfflatusConstant.TXT_PATH_THINK;
   // String path = AfflatusConstant.TXT_PATH_THINK_BOOK;
   // String path=bookFile;

   // String tempPath=AfflatusConstant. TEMP_PATH;
   // String tempPath=AfflatusConstant. TEMP_PATH_LX;
   // String tempPath=bookTemp;

    @PreAuthorize("hasRole('ROLE_normal')")
    //分页查询所有书籍
    @ApiOperation(value = "书籍展示")
    @GetMapping("getPageTxtBook")
    public String getFilePageTxtBook(
            @RequestParam(value="condition",defaultValue="")String condition,
            @RequestParam(value="pn",defaultValue="1")Integer pn,
            Model model) {

        Page<SuperBookfile> pageBook = new Page<>(pn,5);
        //request.setAttribute("jumpUrl", "/index?&pn=");
        model.addAttribute("jumpUrl", "/getPageTxtBook?pn=");
        QueryWrapper<SuperBookfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("book_name",condition);
        final IPage<SuperBookfile> page = superBookfileService.page(pageBook, queryWrapper);

        List<SuperBookfile> list = pageBook.getRecords();//获取数据集合
      //  String bookUrl = list.get(0).getBookUrl();
        model.addAttribute("page",page);
        model.addAttribute("list",list);
        model.addAttribute("bookUrl",bookFile);

        return "page/book/book";

    }


    @PreAuthorize("hasRole('ROLE_admin')")
    @ApiOperation(value = "书籍初始化")
    @GetMapping("initFileBook")
    public String initFileBook(){
       //先清空书籍表中数据
        superBookfileService.remove(null);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

        File file = new File(bookFile);
        if(!file.exists())
        {
            try {
                file.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        File[] listFiles = file.listFiles();
        for (File filename : listFiles) {
            if(!filename.isDirectory()) {
                //获取文件名
                String filetxtname =filename.getName();
                //获取文件大小
                long fileSize=(filename.length()/1024+1);
                //获取最终修改时间
                long lastModified = filename.lastModified();
                calendar.setTimeInMillis(lastModified);
                String fileTime = format.format(calendar.getTime());

                //这里插入数据库可能由于字符编码问题报错
                //  ALTER TABLE insure_user CHANGE nickname nickname VARCHAR(64) CHARACTER SET utf8mb4 ;

                //将数据插入到数据库中
                SuperBookfile superBookfile = new SuperBookfile();
                superBookfile.setBookName(filetxtname);
                superBookfile.setBookSize(fileSize);
                superBookfile.setBookTime(fileTime);
                superBookfile.setBookUrl(bookFile);

                superBookfileService.save(superBookfile);

            }

        }

        return "redirect:getPageTxtBook";
    }



    @ApiOperation(value = "书籍下载")
    @GetMapping("/downbook")
    public void downloadFileTxtBook(@RequestParam(value="fileName",defaultValue="")String fileName,
                                    HttpServletRequest request, HttpServletResponse response) throws IOException {
        //该方法下载中文文件时获取不到中文文件名称
        //response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(TxtName, "UTF-8"));

        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );

        System.out.println("获取到的文件名"+fileName);
        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
            FileInputStream inputStream = new FileInputStream(bookFile+fileName);
            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }



  @ApiOperation(value = "书籍批量下载")
    @GetMapping("BatchBookdown")
    public void BatchBookdown(@RequestParam(value="filenmes",defaultValue="")List<String> filenmes,
                              HttpServletRequest request,HttpServletResponse response) throws IOException{
        List<File> fileList = new ArrayList<>();
        for (String name : filenmes) {
           File file = new File(bookFile+name);
            fileList.add(file);
        }

        //注意AppConst. TEMP_PATH 拒绝访问 一定要设置问文件 不能是目录
      File zipPath = new File(bookTemp);

      DownloadUtils.zipFiles(response, fileList, zipPath);
    }




}

